{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5abe2121-5381-46d7-a849-66f921883972",
   "metadata": {},
   "source": [
    "# LangChain 核心模块：Data Conneciton - Document Loaders\n",
    "\n",
    "使用文档加载器从源中加载数据作为文档。一个文档是一段文字和相关的元数据。\n",
    "\n",
    "![](https://python.langchain.com/assets/images/data_connection-95ff2033a8faa5f3ba41376c0f6dd32a.jpg)\n",
    "\n",
    "\n",
    "例如，有用于加载简单 .txt 文件的文档加载器，用于加载 ArXiv 论文，或者任何网页的文本内容\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df8d7408-b14f-4cfb-84c0-9c0bae958cce",
   "metadata": {},
   "source": [
    "### Document 类\n",
    "\n",
    "这段代码定义了一个名为`Document`的类，允许用户与文档的内容进行交互，可以查看文档的段落、摘要，以及使用查找功能来查询文档中的特定字符串。\n",
    "\n",
    "```python\n",
    "# 基于BaseModel定义的文档类。\n",
    "class Document(BaseModel):\n",
    "    \"\"\"接口，用于与文档进行交互。\"\"\"\n",
    "\n",
    "    # 文档的主要内容。\n",
    "    page_content: str\n",
    "    # 用于查找的字符串。\n",
    "    lookup_str: str = \"\"\n",
    "    # 查找的索引，初次默认为0。\n",
    "    lookup_index = 0\n",
    "    # 用于存储任何与文档相关的元数据。\n",
    "    metadata: dict = Field(default_factory=dict)\n",
    "\n",
    "    @property\n",
    "    def paragraphs(self) -> List[str]:\n",
    "        \"\"\"页面的段落列表。\"\"\"\n",
    "        # 使用\"\\n\\n\"将内容分割为多个段落。\n",
    "        return self.page_content.split(\"\\n\\n\")\n",
    "\n",
    "    @property\n",
    "    def summary(self) -> str:\n",
    "        \"\"\"页面的摘要（即第一段）。\"\"\"\n",
    "        # 返回第一个段落作为摘要。\n",
    "        return self.paragraphs[0]\n",
    "\n",
    "    # 这个方法模仿命令行中的查找功能。\n",
    "    def lookup(self, string: str) -> str:\n",
    "        \"\"\"在页面中查找一个词，模仿cmd-F功能。\"\"\"\n",
    "        # 如果输入的字符串与当前的查找字符串不同，则重置查找字符串和索引。\n",
    "        if string.lower() != self.lookup_str:\n",
    "            self.lookup_str = string.lower()\n",
    "            self.lookup_index = 0\n",
    "        else:\n",
    "            # 如果输入的字符串与当前的查找字符串相同，则查找索引加1。\n",
    "            self.lookup_index += 1\n",
    "        # 找出所有包含查找字符串的段落。\n",
    "        lookups = [p for p in self.paragraphs if self.lookup_str in p.lower()]\n",
    "        # 根据查找结果返回相应的信息。\n",
    "        if len(lookups) == 0:\n",
    "            return \"No Results\"\n",
    "        elif self.lookup_index >= len(lookups):\n",
    "            return \"No More Results\"\n",
    "        else:\n",
    "            result_prefix = f\"(Result {self.lookup_index + 1}/{len(lookups)})\"\n",
    "            return f\"{result_prefix} {lookups[self.lookup_index]}\"\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "874cb92c-cae7-49c3-b21c-78c8595b2799",
   "metadata": {},
   "source": [
    "### BaseLoader 类定义\n",
    "\n",
    "`BaseLoader` 类定义了如何从不同的数据源加载文档，并提供了一个可选的方法来分割加载的文档。使用这个类作为基础，开发者可以为特定的数据源创建自定义的加载器，并确保所有这些加载器都提供了加载数据的方法。load_and_split方法还提供了一个额外的功能，可以根据需要将加载的文档分割为更小的块。\n",
    "\n",
    "```python\n",
    "# 基础加载器类。\n",
    "class BaseLoader(ABC):\n",
    "    \"\"\"基础加载器类定义。\"\"\"\n",
    "\n",
    "    # 抽象方法，所有子类必须实现此方法。\n",
    "    @abstractmethod\n",
    "    def load(self) -> List[Document]:\n",
    "        \"\"\"加载数据并将其转换为文档对象。\"\"\"\n",
    "\n",
    "    # 该方法可以加载文档，并将其分割为更小的块。\n",
    "    def load_and_split(\n",
    "        self, text_splitter: Optional[TextSplitter] = None\n",
    "    ) -> List[Document]:\n",
    "        \"\"\"加载文档并分割成块。\"\"\"\n",
    "        # 如果没有提供特定的文本分割器，使用默认的字符文本分割器。\n",
    "        if text_splitter is None:\n",
    "            _text_splitter: TextSplitter = RecursiveCharacterTextSplitter()\n",
    "        else:\n",
    "            _text_splitter = text_splitter\n",
    "        # 先加载文档。\n",
    "        docs = self.load()\n",
    "        # 然后使用_text_splitter来分割每一个文档。\n",
    "        return _text_splitter.split_documents(docs)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ea65837-6573-42f4-b045-04374578a7d4",
   "metadata": {},
   "source": [
    "## 使用 TextLoader 加载 Txt 文件\n",
    "\n",
    "基于文件格式的内置 Loaders: https://python.langchain.com/docs/modules/data_connection/document_loaders/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "57f7a6d2-cb8e-4504-a04c-037645976ec9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "\n",
    "docs = TextLoader('../tests/state_of_the_union.txt',encoding='utf-8').load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "34a22c21-557d-45bd-a73b-49206a98f132",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(metadata={'source': '../tests/state_of_the_union.txt'}, page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.  \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \\n\\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. \\n\\nIn this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. \\n\\nLet each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. \\n\\nPlease rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. \\n\\nThroughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos.   \\n\\nThey keep moving.   \\n\\nAnd the costs and the threats to America and the world keep rising.   \\n\\nThat’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. \\n\\nThe United States is a member along with 29 other nations. \\n\\nIt matters. American diplomacy matters. American resolve matters. \\n\\nPutin’s latest attack on Ukraine was premeditated and unprovoked. \\n\\nHe rejected repeated efforts at diplomacy. \\n\\nHe thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready.  Here is what we did.   \\n\\nWe prepared extensively and carefully. \\n\\nWe spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. \\n\\nI spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression.  \\n\\nWe countered Russia’s lies with truth.   \\n\\nAnd now that he has acted the free world is holding him accountable. \\n\\nAlong with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. \\n\\nWe are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. \\n\\nTogether with our allies –we are right now enforcing powerful economic sanctions. \\n\\nWe are cutting off Russia’s largest banks from the international financial system.  \\n\\nPreventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund” worthless.   \\n\\nWe are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come.  \\n\\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. \\n\\nThe U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs.  \\n\\nWe are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains. \\n\\nAnd tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. \\n\\nThe Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. \\n\\nTogether with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. \\n\\nWe are giving more than $1 Billion in direct assistance to Ukraine. \\n\\nAnd we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering.  \\n\\nLet me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine.  \\n\\nOur forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west.  \\n\\nFor that purpose we’ve mobilized American ground forces, air squadrons, and ship deployments to protect NATO countries including Poland, Romania, Latvia, Lithuania, and Estonia. \\n\\nAs I have made crystal clear the United States and our Allies will defend every inch of territory of NATO countries with the full force of our collective power.  \\n\\nAnd we remain clear-eyed. The Ukrainians are fighting back with pure courage. But the next few days weeks, months, will be hard on them.  \\n\\nPutin has unleashed violence and chaos.  But while he may make gains on the battlefield – he will pay a continuing high price over the long run. \\n\\nAnd a proud Ukrainian people, who have known 30 years  of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards.  \\n\\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \\n\\nAnd I’m taking robust action to make sure the pain of our sanctions  is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \\n\\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.  \\n\\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.  \\n\\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \\n\\nBut I want you to know that we are going to be okay. \\n\\nWhen the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. \\n\\nWhile it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly. \\n\\nWe see the unity among leaders of nations and a more unified Europe a more unified West. And we see unity among the people who are gathering in cities in large crowds around the world even in Russia to demonstrate their support for Ukraine.  \\n\\nIn the battle between democracy and autocracy, democracies are rising to the moment, and the world is clearly choosing the side of peace and security. \\n\\nThis is a real test. It’s going to take time. So let us continue to draw inspiration from the iron will of the Ukrainian people. \\n\\nTo our fellow Ukrainian Americans who forge a deep bond that connects our two nations we stand with you. \\n\\nPutin may circle Kyiv with tanks, but he will never gain the hearts and souls of the Ukrainian people. \\n\\nHe will never extinguish their love of freedom. He will never weaken the resolve of the free world. \\n\\nWe meet tonight in an America that has lived through two of the hardest years this nation has ever faced. \\n\\nThe pandemic has been punishing. \\n\\nAnd so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. \\n\\nI understand. \\n\\nI remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. \\n\\nThat’s why one of the first things I did as President was fight to pass the American Rescue Plan.  \\n\\nBecause people were hurting. We needed to act, and we did. \\n\\nFew pieces of legislation have done more in a critical moment in our history to lift us out of crisis. \\n\\nIt fueled our efforts to vaccinate the nation and combat COVID-19. It delivered immediate economic relief for tens of millions of Americans.  \\n\\nHelped put food on their table, keep a roof over their heads, and cut the cost of health insurance. \\n\\nAnd as my Dad used to say, it gave people a little breathing room. \\n\\nAnd unlike the $2 Trillion tax cut passed in the previous administration that benefitted the top 1% of Americans, the American Rescue Plan helped working people—and left no one behind. \\n\\nAnd it worked. It created jobs. Lots of jobs. \\n\\nIn fact—our economy created over 6.5 Million new jobs just last year, more jobs created in one year  \\nthan ever before in the history of America. \\n\\nOur economy grew at a rate of 5.7% last year, the strongest growth in nearly 40 years, the first step in bringing fundamental change to an economy that hasn’t worked for the working people of this nation for too long.  \\n\\nFor the past 40 years we were told that if we gave tax breaks to those at the very top, the benefits would trickle down to everyone else. \\n\\nBut that trickle-down theory led to weaker economic growth, lower wages, bigger deficits, and the widest gap between those at the top and everyone else in nearly a century. \\n\\nVice President Harris and I ran for office with a new economic vision for America. \\n\\nInvest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up  \\nand the middle out, not from the top down.  \\n\\nBecause we know that when the middle class grows, the poor have a ladder up and the wealthy do very well. \\n\\nAmerica used to have the best roads, bridges, and airports on Earth. \\n\\nNow our infrastructure is ranked 13th in the world. \\n\\nWe won’t be able to compete for the jobs of the 21st Century if we don’t fix that. \\n\\nThat’s why it was so important to pass the Bipartisan Infrastructure Law—the most sweeping investment to rebuild America in history. \\n\\nThis was a bipartisan effort, and I want to thank the members of both parties who worked to make it happen. \\n\\nWe’re done talking about infrastructure weeks. \\n\\nWe’re going to have an infrastructure decade. \\n\\nIt is going to transform America and put us on a path to win the economic competition of the 21st Century that we face with the rest of the world—particularly with China.  \\n\\nAs I’ve told Xi Jinping, it is never a good bet to bet against the American people. \\n\\nWe’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America. \\n\\nAnd we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice. \\n\\nWe’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities. \\n\\n4,000 projects have already been announced. \\n\\nAnd tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair. \\n\\nWhen we use taxpayer dollars to rebuild America – we are going to Buy American: buy American products to support American jobs. \\n\\nThe federal government spends about $600 Billion a year to keep the country safe and secure. \\n\\nThere’s been a law on the books for almost a century \\nto make sure taxpayers’ dollars support American jobs and businesses. \\n\\nEvery Administration says they’ll do it, but we are actually doing it. \\n\\nWe will buy American to make sure everything from the deck of an aircraft carrier to the steel on highway guardrails are made in America. \\n\\nBut to compete for the best jobs of the future, we also need to level the playing field with China and other competitors. \\n\\nThat’s why it is so important to pass the Bipartisan Innovation Act sitting in Congress that will make record investments in emerging technologies and American manufacturing. \\n\\nLet me give you one example of why it’s so important to pass it. \\n\\nIf you travel 20 miles east of Columbus, Ohio, you’ll find 1,000 empty acres of land. \\n\\nIt won’t look like much, but if you stop and look closely, you’ll see a “Field of dreams,” the ground on which America’s future will be built. \\n\\nThis is where Intel, the American company that helped build Silicon Valley, is going to build its $20 billion semiconductor “mega site”. \\n\\nUp to eight state-of-the-art factories in one place. 10,000 new good-paying jobs. \\n\\nSome of the most sophisticated manufacturing in the world to make computer chips the size of a fingertip that power the world and our everyday lives. \\n\\nSmartphones. The Internet. Technology we have yet to invent. \\n\\nBut that’s just the beginning. \\n\\nIntel’s CEO, Pat Gelsinger, who is here tonight, told me they are ready to increase their investment from  \\n$20 billion to $100 billion. \\n\\nThat would be one of the biggest investments in manufacturing in American history. \\n\\nAnd all they’re waiting for is for you to pass this bill. \\n\\nSo let’s not wait any longer. Send it to my desk. I’ll sign it.  \\n\\nAnd we will really take off. \\n\\nAnd Intel is not alone. \\n\\nThere’s something happening in America. \\n\\nJust look around and you’ll see an amazing story. \\n\\nThe rebirth of the pride that comes from stamping products “Made In America.” The revitalization of American manufacturing.   \\n\\nCompanies are choosing to build new factories here, when just a few years ago, they would have built them overseas. \\n\\nThat’s what is happening. Ford is investing $11 billion to build electric vehicles, creating 11,000 jobs across the country. \\n\\nGM is making the largest investment in its history—$7 billion to build electric vehicles, creating 4,000 jobs in Michigan. \\n\\nAll told, we created 369,000 new manufacturing jobs in America just last year. \\n\\nPowered by people I’ve met like JoJo Burgess, from generations of union steelworkers from Pittsburgh, who’s here with us tonight. \\n\\nAs Ohio Senator Sherrod Brown says, “It’s time to bury the label “Rust Belt.” \\n\\nIt’s time. \\n\\nBut with all the bright spots in our economy, record job growth and higher wages, too many families are struggling to keep up with the bills.  \\n\\nInflation is robbing them of the gains they might otherwise feel. \\n\\nI get it. That’s why my top priority is getting prices under control. \\n\\nLook, our economy roared back faster than most predicted, but the pandemic meant that businesses had a hard time hiring enough workers to keep up production in their factories. \\n\\nThe pandemic also disrupted global supply chains. \\n\\nWhen factories close, it takes longer to make goods and get them from the warehouse to the store, and prices go up. \\n\\nLook at cars. \\n\\nLast year, there weren’t enough semiconductors to make all the cars that people wanted to buy. \\n\\nAnd guess what, prices of automobiles went up. \\n\\nSo—we have a choice. \\n\\nOne way to fight inflation is to drive down wages and make Americans poorer.  \\n\\nI have a better plan to fight inflation. \\n\\nLower your costs, not your wages. \\n\\nMake more cars and semiconductors in America. \\n\\nMore infrastructure and innovation in America. \\n\\nMore goods moving faster and cheaper in America. \\n\\nMore jobs where you can earn a good living in America. \\n\\nAnd instead of relying on foreign supply chains, let’s make it in America. \\n\\nEconomists call it “increasing the productive capacity of our economy.” \\n\\nI call it building a better America. \\n\\nMy plan to fight inflation will lower your costs and lower the deficit. \\n\\n17 Nobel laureates in economics say my plan will ease long-term inflationary pressures. Top business leaders and most Americans support my plan. And here’s the plan: \\n\\nFirst – cut the cost of prescription drugs. Just look at insulin. One in ten Americans has diabetes. In Virginia, I met a 13-year-old boy named Joshua Davis.  \\n\\nHe and his Dad both have Type 1 diabetes, which means they need insulin every day. Insulin costs about $10 a vial to make.  \\n\\nBut drug companies charge families like Joshua and his Dad up to 30 times more. I spoke with Joshua’s mom. \\n\\nImagine what it’s like to look at your child who needs insulin and have no idea how you’re going to pay for it.  \\n\\nWhat it does to your dignity, your ability to look your child in the eye, to be the parent you expect to be. \\n\\nJoshua is here with us tonight. Yesterday was his birthday. Happy birthday, buddy.  \\n\\nFor Joshua, and for the 200,000 other young people with Type 1 diabetes, let’s cap the cost of insulin at $35 a month so everyone can afford it.  \\n\\nDrug companies will still do very well. And while we’re at it let Medicare negotiate lower prices for prescription drugs, like the VA already does. \\n\\nLook, the American Rescue Plan is helping millions of families on Affordable Care Act plans save $2,400 a year on their health care premiums. Let’s close the coverage gap and make those savings permanent. \\n\\nSecond – cut energy costs for families an average of $500 a year by combatting climate change.  \\n\\nLet’s provide investments and tax credits to weatherize your homes and businesses to be energy efficient and you get a tax credit; double America’s clean energy production in solar, wind, and so much more;  lower the price of electric vehicles, saving you another $80 a month because you’ll never have to pay at the gas pump again. \\n\\nThird – cut the cost of child care. Many families pay up to $14,000 a year for child care per child.  \\n\\nMiddle-class and working families shouldn’t have to pay more than 7% of their income for care of young children.  \\n\\nMy plan will cut the cost in half for most families and help parents, including millions of women, who left the workforce during the pandemic because they couldn’t afford child care, to be able to get back to work. \\n\\nMy plan doesn’t stop there. It also includes home and long-term care. More affordable housing. And Pre-K for every 3- and 4-year-old.  \\n\\nAll of these will lower costs. \\n\\nAnd under my plan, nobody earning less than $400,000 a year will pay an additional penny in new taxes. Nobody.  \\n\\nThe one thing all Americans agree on is that the tax system is not fair. We have to fix it.  \\n\\nI’m not looking to punish anyone. But let’s make sure corporations and the wealthiest Americans start paying their fair share. \\n\\nJust last year, 55 Fortune 500 corporations earned $40 billion in profits and paid zero dollars in federal income tax.  \\n\\nThat’s simply not fair. That’s why I’ve proposed a 15% minimum tax rate for corporations. \\n\\nWe got more than 130 countries to agree on a global minimum tax rate so companies can’t get out of paying their taxes at home by shipping jobs and factories overseas. \\n\\nThat’s why I’ve proposed closing loopholes so the very wealthy don’t pay a lower tax rate than a teacher or a firefighter.  \\n\\nSo that’s my plan. It will grow the economy and lower costs for families. \\n\\nSo what are we waiting for? Let’s get this done. And while you’re at it, confirm my nominees to the Federal Reserve, which plays a critical role in fighting inflation.  \\n\\nMy plan will not only lower costs to give families a fair shot, it will lower the deficit. \\n\\nThe previous Administration not only ballooned the deficit with tax cuts for the very wealthy and corporations, it undermined the watchdogs whose job was to keep pandemic relief funds from being wasted. \\n\\nBut in my administration, the watchdogs have been welcomed back. \\n\\nWe’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans.  \\n\\nAnd tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. \\n\\nBy the end of this year, the deficit will be down to less than half what it was before I took office.  \\n\\nThe only president ever to cut the deficit by more than one trillion dollars in a single year. \\n\\nLowering your costs also means demanding more competition. \\n\\nI’m a capitalist, but capitalism without competition isn’t capitalism. \\n\\nIt’s exploitation—and it drives up prices. \\n\\nWhen corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under. \\n\\nWe see it happening with ocean carriers moving goods in and out of America. \\n\\nDuring the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits. \\n\\nTonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \\n\\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up.  \\n\\nThat ends on my watch. \\n\\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \\n\\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \\n\\nLet’s pass the Paycheck Fairness Act and paid leave.  \\n\\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \\n\\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges. \\n\\nAnd let’s pass the PRO Act when a majority of workers want to form a union—they shouldn’t be stopped.  \\n\\nWhen we invest in our workers, when we build the economy from the bottom up and the middle out together, we can do something we haven’t done in a long time: build a better America. \\n\\nFor more than two years, COVID-19 has impacted every decision in our lives and the life of the nation. \\n\\nAnd I know you’re tired, frustrated, and exhausted. \\n\\nBut I also know this. \\n\\nBecause of the progress we’ve made, because of your resilience and the tools we have, tonight I can say  \\nwe are moving forward safely, back to more normal routines.  \\n\\nWe’ve reached a new moment in the fight against COVID-19, with severe cases down to a level not seen since last July.  \\n\\nJust a few days ago, the Centers for Disease Control and Prevention—the CDC—issued new mask guidelines. \\n\\nUnder these new guidelines, most Americans in most of the country can now be mask free.   \\n\\nAnd based on the projections, more of the country will reach that point across the next couple of weeks. \\n\\nThanks to the progress we have made this past year, COVID-19 need no longer control our lives.  \\n\\nI know some are talking about “living with COVID-19”. Tonight – I say that we will never just accept living with COVID-19. \\n\\nWe will continue to combat the virus as we do other diseases. And because this is a virus that mutates and spreads, we will stay on guard. \\n\\nHere are four common sense steps as we move forward safely.  \\n\\nFirst, stay protected with vaccines and treatments. We know how incredibly effective vaccines are. If you’re vaccinated and boosted you have the highest degree of protection. \\n\\nWe will never give up on vaccinating more Americans. Now, I know parents with kids under 5 are eager to see a vaccine authorized for their children. \\n\\nThe scientists are working hard to get that done and we’ll be ready with plenty of vaccines when they do. \\n\\nWe’re also ready with anti-viral treatments. If you get COVID-19, the Pfizer pill reduces your chances of ending up in the hospital by 90%.  \\n\\nWe’ve ordered more of these pills than anyone in the world. And Pfizer is working overtime to get us 1 Million pills this month and more than double that next month.  \\n\\nAnd we’re launching the “Test to Treat” initiative so people can get tested at a pharmacy, and if they’re positive, receive antiviral pills on the spot at no cost.  \\n\\nIf you’re immunocompromised or have some other vulnerability, we have treatments and free high-quality masks. \\n\\nWe’re leaving no one behind or ignoring anyone’s needs as we move forward. \\n\\nAnd on testing, we have made hundreds of millions of tests available for you to order for free.   \\n\\nEven if you already ordered free tests tonight, I am announcing that you can order more from covidtests.gov starting next week. \\n\\nSecond – we must prepare for new variants. Over the past year, we’ve gotten much better at detecting new variants. \\n\\nIf necessary, we’ll be able to deploy new vaccines within 100 days instead of many more months or years.  \\n\\nAnd, if Congress provides the funds we need, we’ll have new stockpiles of tests, masks, and pills ready if needed. \\n\\nI cannot promise a new variant won’t come. But I can promise you we’ll do everything within our power to be ready if it does.  \\n\\nThird – we can end the shutdown of schools and businesses. We have the tools we need. \\n\\nIt’s time for Americans to get back to work and fill our great downtowns again.  People working from home can feel safe to begin to return to the office.   \\n\\nWe’re doing that here in the federal government. The vast majority of federal workers will once again work in person. \\n\\nOur schools are open. Let’s keep it that way. Our kids need to be in school. \\n\\nAnd with 75% of adult Americans fully vaccinated and hospitalizations down by 77%, most Americans can remove their masks, return to work, stay in the classroom, and move forward safely. \\n\\nWe achieved this because we provided free vaccines, treatments, tests, and masks. \\n\\nOf course, continuing this costs money. \\n\\nI will soon send Congress a request. \\n\\nThe vast majority of Americans have used these tools and may want to again, so I expect Congress to pass it quickly.   \\n\\nFourth, we will continue vaccinating the world.     \\n\\nWe’ve sent 475 Million vaccine doses to 112 countries, more than any other nation. \\n\\nAnd we won’t stop. \\n\\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \\n\\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease.  \\n\\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans.  \\n\\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \\n\\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \\n\\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \\n\\nOfficer Mora was 27 years old. \\n\\nOfficer Rivera was 22. \\n\\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \\n\\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \\n\\nI’ve worked on these issues a long time. \\n\\nI know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. \\n\\nSo let’s not abandon our streets. Or choose between safety and equal justice. \\n\\nLet’s come together to protect our communities, restore trust, and hold law enforcement accountable. \\n\\nThat’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. \\n\\nThat’s why the American Rescue Plan provided $350 Billion that cities, states, and counties can use to hire more police and invest in proven strategies like community violence interruption—trusted messengers breaking the cycle of violence and trauma and giving young people hope.  \\n\\nWe should all agree: The answer is not to Defund the police. The answer is to FUND the police with the resources and training they need to protect our communities. \\n\\nI ask Democrats and Republicans alike: Pass my budget and keep our neighborhoods safe.  \\n\\nAnd I will keep doing everything in my power to crack down on gun trafficking and ghost guns you can buy online and make at home—they have no serial numbers and can’t be traced. \\n\\nAnd I ask Congress to pass proven measures to reduce gun violence. Pass universal background checks. Why should anyone on a terrorist list be able to purchase a weapon? \\n\\nBan assault weapons and high-capacity magazines. \\n\\nRepeal the liability shield that makes gun manufacturers the only industry in America that can’t be sued. \\n\\nThese laws don’t infringe on the Second Amendment. They save lives. \\n\\nThe most fundamental right in America is the right to vote – and to have it counted. And it’s under assault. \\n\\nIn state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. \\n\\nA former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \\n\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.  \\n\\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.  \\n\\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. \\n\\nWe can do all this while keeping lit the torch of liberty that has led generations of immigrants to this land—my forefathers and so many of yours. \\n\\nProvide a pathway to citizenship for Dreamers, those on temporary status, farm workers, and essential workers. \\n\\nRevise our laws so businesses have the workers they need and families don’t wait decades to reunite. \\n\\nIt’s not only the right thing to do—it’s the economically smart thing to do. \\n\\nThat’s why immigration reform is supported by everyone from labor unions to religious leaders to the U.S. Chamber of Commerce. \\n\\nLet’s get it done once and for all. \\n\\nAdvancing liberty and justice also requires protecting the rights of women. \\n\\nThe constitutional right affirmed in Roe v. Wade—standing precedent for half a century—is under attack as never before. \\n\\nIf we want to go forward—not backward—we must protect access to health care. Preserve a woman’s right to choose. And let’s continue to advance maternal health care in America. \\n\\nAnd for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \\n\\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \\n\\nWhile it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \\n\\nAnd soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \\n\\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together.  \\n\\nFirst, beat the opioid epidemic. \\n\\nThere is so much we can do. Increase funding for prevention, treatment, harm reduction, and recovery.  \\n\\nGet rid of outdated rules that stop doctors from prescribing treatments. And stop the flow of illicit drugs by working with state and local law enforcement to go after traffickers. \\n\\nIf you’re suffering from addiction, know you are not alone. I believe in recovery, and I celebrate the 23 million Americans in recovery. \\n\\nSecond, let’s take on mental health. Especially among our children, whose lives and education have been turned upside down.  \\n\\nThe American Rescue Plan gave schools money to hire teachers and help students make up for lost learning.  \\n\\nI urge every parent to make sure your school does just that. And we can all play a part—sign up to be a tutor or a mentor. \\n\\nChildren were also struggling before the pandemic. Bullying, violence, trauma, and the harms of social media. \\n\\nAs Frances Haugen, who is here with us tonight, has shown, we must hold social media platforms accountable for the national experiment they’re conducting on our children for profit. \\n\\nIt’s time to strengthen privacy protections, ban targeted advertising to children, demand tech companies stop collecting personal data on our children. \\n\\nAnd let’s get all Americans the mental health services they need. More people they can turn to for help, and full parity between physical and mental health care. \\n\\nThird, support our veterans. \\n\\nVeterans are the best of us. \\n\\nI’ve always believed that we have a sacred obligation to equip all those we send to war and care for them and their families when they come home. \\n\\nMy administration is providing assistance with job training and housing, and now helping lower-income veterans get VA care debt-free.  \\n\\nOur troops in Iraq and Afghanistan faced many dangers. \\n\\nOne was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. \\n\\nWhen they came home, many of the world’s fittest and best trained warriors were never the same. \\n\\nHeadaches. Numbness. Dizziness. \\n\\nA cancer that would put them in a flag-draped coffin. \\n\\nI know. \\n\\nOne of those soldiers was my son Major Beau Biden. \\n\\nWe don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. \\n\\nBut I’m committed to finding out everything we can. \\n\\nCommitted to military families like Danielle Robinson from Ohio. \\n\\nThe widow of Sergeant First Class Heath Robinson.  \\n\\nHe was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. \\n\\nStationed near Baghdad, just yards from burn pits the size of football fields. \\n\\nHeath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter. \\n\\nBut cancer from prolonged exposure to burn pits ravaged Heath’s lungs and body. \\n\\nDanielle says Heath was a fighter to the very end. \\n\\nHe didn’t know how to stop fighting, and neither did she. \\n\\nThrough her pain she found purpose to demand we do better. \\n\\nTonight, Danielle—we are. \\n\\nThe VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits. \\n\\nAnd tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers. \\n\\nI’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve. \\n\\nAnd fourth, let’s end cancer as we know it. \\n\\nThis is personal to me and Jill, to Kamala, and to so many of you. \\n\\nCancer is the #2 cause of death in America–second only to heart disease. \\n\\nLast month, I announced our plan to supercharge  \\nthe Cancer Moonshot that President Obama asked me to lead six years ago. \\n\\nOur goal is to cut the cancer death rate by at least 50% over the next 25 years, turn more cancers from death sentences into treatable diseases.  \\n\\nMore support for patients and families. \\n\\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \\n\\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more.  \\n\\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \\n\\nA unity agenda for the nation. \\n\\nWe can do this. \\n\\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \\n\\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \\n\\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \\n\\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \\n\\nNow is the hour. \\n\\nOur moment of responsibility. \\n\\nOur test of resolve and conscience, of history itself. \\n\\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \\n\\nWell I know this nation.  \\n\\nWe will meet the test. \\n\\nTo protect freedom and liberty, to expand fairness and opportunity. \\n\\nWe will save democracy. \\n\\nAs hard as these times have been, I am more optimistic about America today than I have been my whole life. \\n\\nBecause I see the future that is within our grasp. \\n\\nBecause I know there is simply nothing beyond our capacity. \\n\\nWe are the only nation on Earth that has always turned every crisis we have faced into an opportunity. \\n\\nThe only nation that can be defined by a single word: possibilities. \\n\\nSo on this night, in our 245th year as a nation, I have come to report on the State of the Union. \\n\\nAnd my report is this: the State of the Union is strong—because you, the American people, are strong. \\n\\nWe are stronger today than we were a year ago. \\n\\nAnd we will be stronger a year from now than we are today. \\n\\nNow is our moment to meet and overcome the challenges of our time. \\n\\nAnd we will, as one people. \\n\\nOne America. \\n\\nThe United States of America. \\n\\nMay God bless you all. May God protect our troops.')]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "da599362-ae4b-4dbb-9ea3-c4fda6e4019b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "langchain_core.documents.base.Document"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(docs[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "06bd7d1f-ddec-4415-8adb-e17a9d750f16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and th'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0].page_content[:100]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b68fdbcb-b60d-441f-91fc-d8cac24ba3e1",
   "metadata": {},
   "source": [
    "## 使用 ArxivLoader 加载 ArXiv 论文\n",
    "\n",
    "代码实现：https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/document_loaders/arxiv.py\n",
    "\n",
    "### ArxivLoader 类定义\n",
    "\n",
    "`ArxivLoader` 类专门用于从Arxiv平台获取文档。用户提供一个搜索查询，然后加载器与Arxiv API交互，以检索与该查询相关的文档列表。这些文档然后以标准的Document格式返回。\n",
    "\n",
    "```python\n",
    "# 针对Arxiv平台的加载器类。\n",
    "class ArxivLoader(BaseLoader):\n",
    "    \"\"\"从`Arxiv`加载基于搜索查询的文档。\n",
    "\n",
    "    此加载器负责将Arxiv的原始PDF文档转换为纯文本格式，以便于处理。\n",
    "    \"\"\"\n",
    "\n",
    "    # 初始化方法。\n",
    "    def __init__(\n",
    "        self,\n",
    "        query: str,\n",
    "        load_max_docs: Optional[int] = 100,\n",
    "        load_all_available_meta: Optional[bool] = False,\n",
    "    ):\n",
    "        self.query = query\n",
    "        \"\"\"传递给Arxiv API进行搜索的特定查询或关键字。\"\"\"\n",
    "        self.load_max_docs = load_max_docs\n",
    "        \"\"\"从搜索中检索文档的上限。\"\"\"\n",
    "        self.load_all_available_meta = load_all_available_meta\n",
    "        \"\"\"决定是否加载与文档关联的所有元数据的标志。\"\"\"\n",
    "\n",
    "    # 基于查询获取文档的加载方法。\n",
    "    def load(self) -> List[Document]:\n",
    "        arxiv_client = ArxivAPIWrapper(\n",
    "            load_max_docs=self.load_max_docs,\n",
    "            load_all_available_meta=self.load_all_available_meta,\n",
    "        )\n",
    "        docs = arxiv_client.search(self.query)\n",
    "        return docs\n",
    "```\n",
    "\n",
    "ArxivLoader有以下参数：\n",
    "\n",
    "- query：用于在`ArXiv`中查找文档的文本\n",
    "- load_max_docs：默认值为100。使用它来限制下载的文档数量。下载所有100个文档需要时间，因此在实验中请使用较小的数字。\n",
    "- load_all_available_meta：默认值为False。默认情况下只下载最重要的字段：发布日期（文档发布/最后更新日期）、标题、作者、摘要。如果设置为True，则还会下载其他字段。\n",
    "\n",
    "以 **GPT-3 论文（Language Models are Few-Shot Learners）** 为例，展示如何使用 `ArxivLoader`\n",
    "\n",
    "GPT-3 论文的 Arxiv 链接：https://arxiv.org/abs/2005.14165"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8dadd89b-6a13-4391-9102-acde028b61d5",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: arxiv in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (2.1.3)\n",
      "Requirement already satisfied: pymupdf in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (1.24.7)\n",
      "Requirement already satisfied: feedparser~=6.0.10 in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (from arxiv) (6.0.11)\n",
      "Requirement already satisfied: requests~=2.32.0 in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (from arxiv) (2.32.3)\n",
      "Requirement already satisfied: PyMuPDFb==1.24.6 in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (from pymupdf) (1.24.6)\n",
      "Requirement already satisfied: sgmllib3k in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (from feedparser~=6.0.10->arxiv) (1.0.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\programdata\\anaconda3\\envs\\langchain\\lib\\site-packages (from requests~=2.32.0->arxiv) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\programdata\\anaconda3\\envs\\langchain\\lib\\site-packages (from requests~=2.32.0->arxiv) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\programdata\\anaconda3\\envs\\langchain\\lib\\site-packages (from requests~=2.32.0->arxiv) (2.2.2)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\programdata\\anaconda3\\envs\\langchain\\lib\\site-packages (from requests~=2.32.0->arxiv) (2024.2.2)\n"
     ]
    }
   ],
   "source": [
    "# 安装必要依赖包\n",
    "!pip install arxiv pymupdf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0dd56c35-4ed5-4761-982c-4eab041a0581",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import ArxivLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d3d30fca-19d5-4c61-b2fe-5736233cf3ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"2005.14165\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a07458e4-031b-44f0-a154-ce94ee68ea36",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = ArxivLoader(query=query, load_max_docs=5).load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "19fcc12c-6186-4e58-8038-2368efb2ea64",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13175090-a8f8-4d39-bf7a-a4a7621f62a1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "71e17122-4408-4926-b25c-016090f5e21b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Published': '2020-07-22',\n",
       " 'Title': 'Language Models are Few-Shot Learners',\n",
       " 'Authors': 'Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, Tom Henighan, Rewon Child, Aditya Ramesh, Daniel M. Ziegler, Jeffrey Wu, Clemens Winter, Christopher Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, Dario Amodei',\n",
       " 'Summary': \"Recent work has demonstrated substantial gains on many NLP tasks and\\nbenchmarks by pre-training on a large corpus of text followed by fine-tuning on\\na specific task. While typically task-agnostic in architecture, this method\\nstill requires task-specific fine-tuning datasets of thousands or tens of\\nthousands of examples. By contrast, humans can generally perform a new language\\ntask from only a few examples or from simple instructions - something which\\ncurrent NLP systems still largely struggle to do. Here we show that scaling up\\nlanguage models greatly improves task-agnostic, few-shot performance, sometimes\\neven reaching competitiveness with prior state-of-the-art fine-tuning\\napproaches. Specifically, we train GPT-3, an autoregressive language model with\\n175 billion parameters, 10x more than any previous non-sparse language model,\\nand test its performance in the few-shot setting. For all tasks, GPT-3 is\\napplied without any gradient updates or fine-tuning, with tasks and few-shot\\ndemonstrations specified purely via text interaction with the model. GPT-3\\nachieves strong performance on many NLP datasets, including translation,\\nquestion-answering, and cloze tasks, as well as several tasks that require\\non-the-fly reasoning or domain adaptation, such as unscrambling words, using a\\nnovel word in a sentence, or performing 3-digit arithmetic. At the same time,\\nwe also identify some datasets where GPT-3's few-shot learning still struggles,\\nas well as some datasets where GPT-3 faces methodological issues related to\\ntraining on large web corpora. Finally, we find that GPT-3 can generate samples\\nof news articles which human evaluators have difficulty distinguishing from\\narticles written by humans. We discuss broader societal impacts of this finding\\nand of GPT-3 in general.\"}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0].metadata  # meta-information of the Document"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9154c1f-986e-4bf0-be7e-b6b343069987",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d8313d0-430f-4797-8053-5f1855e857f6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "f4770668-42f7-496f-972d-adc6cbd75f0d",
   "metadata": {},
   "source": [
    "## 使用 UnstructuredURLLoader 加载网页内容\n",
    "\n",
    "使用非结构化分区函数(Unstructured)来检测MIME类型并将文件路由到适当的分区器(partitioner)。\n",
    "\n",
    "支持两种模式运行加载程序：\"single\"和\"elements\"。如果使用\"single\"模式，文档将作为单个langchain Document对象返回。如果使用\"elements\"模式，非结构化库将把文档拆分成标题和叙述文本等元素。您可以在mode后面传入其他非结构化kwargs以应用不同的非结构化设置。\n",
    "\n",
    "代码实现：https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/document_loaders/url.py\n",
    "\n",
    "UnstructuredURLLoader 主要参数：\n",
    "\n",
    "- urls：待加载网页 URL 列表\n",
    "- continue_on_failure：默认`True`，某个URL加载失败后，是否继续\n",
    "- mode：默认`single`，\n",
    "\n",
    "\n",
    "以 ReAct 网页为例（https://react-lm.github.io/） 展示使用\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "e43eb375-99d2-457f-9e23-04c7173276b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: python-magic in c:\\programdata\\anaconda3\\envs\\langchain\\lib\\site-packages (0.4.27)\n",
      "Requirement already satisfied: python-magic-bin in c:\\users\\lenovo\\appdata\\roaming\\python\\python310\\site-packages (0.4.14)\n"
     ]
    }
   ],
   "source": [
    "! pip install python-magic\n",
    "! pip install python-magic-bin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "06a4e527-c260-4ff5-857d-933710288fa8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import UnstructuredURLLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a9b7e966-fa6c-49d1-8971-91ce28819bfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "urls = [\n",
    "    \"https://react-lm.github.io/\",\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b15bb069-fa0d-43c1-b64d-84a93f0b2c5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "loader = UnstructuredURLLoader(urls=urls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "eee9b224-c8ff-4434-b988-1f76e722e91a",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = loader.load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f8d83248-e346-4f2d-b1b5-d74812b9accb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'source': 'https://react-lm.github.io/'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[0].metadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "24f9c721-dfd3-4632-a89e-92d2fa9b3594",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ReAct: Synergizing Reasoning and Acting in Language Models\n",
      "\n",
      "Shunyu Yao,\n",
      "\n",
      "Jeffrey Zhao,\n",
      "\n",
      "Dian Yu,\n",
      "\n",
      "Nan Du,\n",
      "\n",
      "Izhak Shafran,\n",
      "\n",
      "Karthik Narasimhan,\n",
      "\n",
      "Yuan Cao\n",
      "\n",
      "[Paper]\n",
      "\n",
      "[Code]\n",
      "\n",
      "[Blogpost]\n",
      "\n",
      "[BibTex]\n",
      "\n",
      "Language models are getting better at reasoning (e.g. chain-of-thought prompting) and acting (e.g. WebGPT, SayCan, ACT-1), but these two directions have remained separate. \n",
      "                ReAct asks, what if these two fundamental capabilities are combined?\n",
      "\n",
      "Abstract\n",
      "\n",
      "While large language models (LLMs) have demonstrated impressive capabilities across tasks in language understanding and interactive decision making, their abilities for reasoning (e.g. chain-of-thought prompting) and acting (e.g. action plan generation) have primarily been studied as separate topics. In this paper, we explore the use of LLMs to generate both reasoning traces and task-specific actions in an interleaved manner, allowing for greater synergy between the two: reasoning traces help the model induce, track, and update action plans as well as handle exceptions, while actions allow it to interface with external sources, such as knowledge bases or environments, to gather additional information. We apply our approach, named ReAct, to a diverse set of language and decision making tasks and demonstrate its effectiveness over state-of-the-art baselines, as well as improved human interpretability and trustworthiness over methods without reasoning or acting components. Concretely, on question answering (HotpotQA) and fact verification (Fever), ReAct overcomes issues of hallucination and error propagation prevalent in chain-of-thought reasoning by interacting with a simple Wikipedia API, and generates human-like task-solving trajectories that are more interpretable than baselines without reasoning traces. On two interactive decision making benchmarks (ALFWorld and WebShop), ReAct outperforms imitation and reinforcement learning methods by an absolute success rate of 34% and 10% respectively, while being prompted with only one or two in-context examples.\n",
      "\n",
      "ReAct Prompting\n",
      "\n",
      "A ReAct prompt consists of few-shot task-solving trajectories, with human-written text reasoning traces and actions, as well as environment observations in response to actions (see examples in paper appendix!) \n",
      "                ReAct prompting is intuitive and flexible to design, and achieves state-of-the-art few-shot performances across a variety of tasks, from question answering to online shopping!\n",
      "\n",
      "HotpotQA Example\n",
      "\n",
      "The reason-only baseline (i.e. chain-of-thought) suffers from misinformation (in red) as it is not grounded to external environments to obtain and update knowledge, and has to rely on limited internal knowledge. \n",
      "                The act-only baseline suffers from the lack of reasoning, unable to synthesize the final answer despite having the same actions and observation as ReAct in this case. \n",
      "                In contrast, ReAct solves the task with a interpretable and factual trajectory.\n",
      "\n",
      "ALFWorld Example\n",
      "\n",
      "For decision making tasks, we design human trajectories with sparse reasoning traces, letting the LM decide when to think vs. act. \n",
      "                ReAct isn't perfect --- below is a failure example on ALFWorld. However, ReAct format allows easy human inspection and behavior correction by changing a couple of model thoughts, an exciting novel approach to human alignment!\n",
      "\n",
      "ReAct Finetuning: Initial Results\n",
      "\n",
      "Prompting has limited context window and learning support. \n",
      "                    Initial finetuning results on HotpotQA using ReAct prompting trajectories suggest:\n",
      "                    (1) ReAct is the best fintuning format across model sizes; \n",
      "                    (2) ReAct finetuned smaller models outperform prompted larger models!\n"
     ]
    }
   ],
   "source": [
    "print(data[0].page_content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ad7894b2-15e4-4f75-8c8e-96314629fb7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "loader = UnstructuredURLLoader(urls=urls, mode=\"elements\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "b01991e5-b2e4-41e4-9774-393a78523ff5",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_data = loader.load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a474b588-dad5-4da8-b748-3b5949934e30",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'ReAct: Synergizing Reasoning and Acting in Language Models'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_data[0].page_content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "de99dd7e-7758-4666-a3fd-86041fd29417",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "23"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(new_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "d9ee6174-ad2f-4864-8253-3cb9b434856d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Shunyu Yao,'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_data[1].page_content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce08049d-6811-4d16-ba5f-0ff417f09077",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
